import statistics

from django.shortcuts import render
from datetime import datetime
from django.utils.dateparse import parse_datetime
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import serializers

from django.http import Http404
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
from .serializers import scheduler, ChannelSerializer, TaskSerializer
from .models import Task, Channel
from rest_framework import viewsets, permissions


# Create your views here.


# def get_request_args(request):
#     content = request.data.get('content')
#     run_time_str = request.data.get('run_time')
#     run_time = parse_datetime(run_time_str)
#
#     year = run_time.year
#     month = run_time.month
#     day = run_time.day
#     hour = run_time.hour
#     minute = run_time.minute
#
#     if not content or not run_time:
#         return Response({"error": "Invalid content or time"}, status=400)
#     my_task_id = int(datetime.timestamp(datetime.now()))
#
#     job_kwargs = {
#         "func": send_dingtalk_job_by_id,
#         "trigger": "cron",
#         "id": str(my_task_id),
#         "kwargs": {"content": content},
#         "year": year,
#         "month": month,
#         "day": day,
#         "hour": hour,
#         "minute": minute,
#         "replace_existing": "true"
#
#     }
#     return job_kwargs
#
# def send_dingtalk_job_by_id(content):
#     print(f"任务内容:--- {content}: {datetime.now()}")


class TestApscheduler(APIView):

    def get(self, request):
        # 查看所有任务
        task_ins = Task.objects.all().filter(author=request.user)
        serializer = TaskSerializer(task_ins, many=True)
        # job_list = scheduler.get_jobs()
        # return Response([{x.name: x.id} for x in job_list])
        return Response(serializer.data)

    def post(self, request):
        serializer = TaskSerializer(data=request.data,
                                    context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        print(serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        # scheduler.add_job(**job_kwargs)
        # return Response({"message": "任务已提交"})


class TestApschedulerDetail(APIView):
    def get(self, request, pk):
        msg = scheduler.get_job(job_id=pk)
        print(f"查看任务id:{msg}")
        return Response({"msg": str(msg)})

    def delete(self, request, task_id):
        select_result = scheduler.get_job(job_id=task_id)
        if select_result:
            job_delete_msg = scheduler.remove_job(job_id=task_id)
            print("任务删除结果:%s" % job_delete_msg)
        task_delete_msg = Task.objects.filter(task_id=task_id).delete()
        print(task_delete_msg)
        # print("任务删除结果:%s" % task_delete_msg)
        # msg = scheduler.remove_job(job_id=task_id)
        # print(f"删除任务id:{str(msg)}")
        return Response({"msg": str(task_delete_msg)})

    def put(self, request, pk):
        action = request.data.get('action')
        content = request.data.get('content')

        if action == "pause":
            msg = scheduler.pause_job(job_id=pk)
            print(f"暂停任务:{str(msg)}")
            return Response({"msg": str(msg)})
        if action == "resume":
            msg = scheduler.resume_job(job_id=pk)
            print(f"恢复任务:{str(msg)}")
            return Response({"msg": str(msg)})
        # if action == "modify":
        #     run_time_str = request.data.get('run_time')
        #     run_time = parse_datetime(run_time_str)
        #
        #     year = run_time.year
        #     month = run_time.month
        #     day = run_time.day
        #     hour = run_time.hour
        #     minute = run_time.minute
        #     job_kwargs = {
        #         "func": send_dingtalk_job_by_id,
        #         "trigger": "cron",
        #         "id": pk,
        #         "kwargs": {"content": content},
        #         "year": year,
        #         "month": month,
        #         "day": day,
        #         "hour": hour,
        #         "minute": minute,
        #         "replace_existing": "true"
        #     }
        #     # msg = scheduler.reschedule_job(job_kwargs)
        #     del_msg = scheduler.remove_job(job_id=pk)
        #     create_msg = scheduler.add_job(**job_kwargs)
        #     return Response({"修改任务:": str(create_msg)})
        return Response({"msg": "error"})


# class ChannelDetail(APIView):
#     def get(self, request, format=None):
#         channel_ins = Channel.objects.all().filter(author=request.user)
#         serializer = ChannelSerializer(channel_ins, many=True)
#         return Response(serializer.data)
#
#     def post(self, request, format=None):
#         serializer = ChannelSerializer(
#             data=request.data,
#             context={'request': request}
#         )
#         if serializer.is_valid():
#             serializer.save(author=request.user)
#             return Response(serializer.data, status=status.HTTP_201_CREATED)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#
# class ChannelInfo(APIView):
#     def put(self, request, channel_name):
#
class ChannelViewSet(viewsets.ModelViewSet):
    queryset = Channel.objects.all()
    serializer_class = ChannelSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        """确保用户只能看到自己创建的Channel"""
        print(Channel.objects.filter(author=self.request.user))
        return self.queryset.filter(author=self.request.user)

    def perform_create(self, serializer):
        """创建时自动设置作者为当前用户"""
        serializer.save(author=self.request.user)

    def destroy(self, request, *args, **kwargs):
        """删除功能"""
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def update(self, request, *args, **kwargs):
        """更新功能"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(serializer.data)